package com.local.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cz073586.ffmpeg.manager.ProcessMaager;
import com.cz073586.tools.util.Tools;
import com.cz073586.tools.util.UUIDGenerateUtil;
import com.local.dao.mapers.CrossingToEquipmentMapper;
import com.local.dao.mapers.EquipmentToMedieMapper;
import com.local.dao.mapers.LocalEquipmentMapper;
import com.local.dao.mapers.LocalStationMapper;
import com.local.entity.ex.LocalEquipmentEx;
import com.local.manager.cfgManager.MediaCfgManager;
import com.local.model.CrossingToEquipmentExample;
import com.local.model.EquipmentToMedie;
import com.local.model.EquipmentToMedieExample;
import com.local.model.LocalEquipment;
import com.local.model.LocalEquipmentExample;
import com.local.model.LocalStation;
import com.local.page.LocalEquipmentPage;
import com.local.service.face.LocalEquipmentService;
import com.local.service.face.LogService;
import com.local.service.face.StreamingMediaService;
import com.qianhai.common.dao.face.BaseMapper;
import com.qianhai.common.exception.BaseException;
import com.qianhai.common.service.impl.BaseServiceImpl;
import com.qianhai.common.utils.BeanUtil;

@Service
public class LocalEquipmentServiceImpl extends
		BaseServiceImpl<LocalEquipmentExample, LocalEquipment, String>
		implements LocalEquipmentService
{
	
	@Autowired
	private LocalEquipmentMapper localEquipmentMapper;
	@Autowired
	private LocalStationMapper localStationMapper;
	@Autowired
	private EquipmentToMedieMapper equimentToMedieMapper;
	
	@Autowired
	private StreamingMediaService streamService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
	private CrossingToEquipmentMapper croToEquimentMpper;
	
	@Override
	public List<LocalEquipment> queryDeviceByPage(
			LocalEquipmentPage<LocalEquipment> page)
	{
		try
		{
			Integer recordCount = localEquipmentMapper.countAllByPage(page);
			page.setTotalRecords(recordCount);
			List<LocalEquipment> list = localEquipmentMapper.queryByPage(page);
			
			// 添加岗亭名
			List<LocalEquipment> listEx = new ArrayList<LocalEquipment>();
			
			for (LocalEquipment ep : list)
			{
				LocalEquipmentEx ex = new LocalEquipmentEx();
				BeanUtil.copyProperties(ex, ep);
				LocalStation station = localStationMapper.selectByPrimaryKey(ep
						.getStationUuid());
				if (!Tools.isEmpty(station))
				{
					ex.setStateName(station.getStationName());
				}
				
				// 相机连接状态
				EquipmentToMedie medieInfo = getMedieInfoByEquimentId(ep
						.getEquipmentUuid());
				if (!Tools.isEmpty(medieInfo))
				{
					Runnable runble = ProcessMaager.instance().getRunbleMaper()
							.get(medieInfo.getProcessId());
					if (!Tools.isEmpty(runble))
					{
						ex.setStuts(1);
					}
				}
				listEx.add(ex);
			}
			
			page.setData(listEx);
			return listEx;
		} catch (Exception e)
		{
			throw new BaseException("", e);
		}
	}
	
	@Override
	public int registerEquipment(LocalEquipment equipment) throws BaseException
	{
		try
		{
			if (Tools.isEmpty(equipment.getExchangeNo()))
			{
				throw new BaseException("90000-00001-00001");
			}
			
			if (Tools.isEmpty(equipment.getCameraNo()))
			{
				throw new BaseException("90000-00001-00002");
			}
			// 检查重复注册，如果已经注册则删除
			LocalEquipmentExample ex = new LocalEquipmentExample();
			ex.or().andCameraNoEqualTo(equipment.getCameraNo().trim())
					.andExchangeNoEqualTo(equipment.getExchangeNo().trim());
			List<LocalEquipment> list = localEquipmentMapper
					.selectByCondition(ex);
			
			if (!list.isEmpty())
			{
				LocalEquipment localEquipment = list.get(0);
				localEquipment.setInstallEffect(equipment.getInstallEffect());
				localEquipment.setInstallPosition(equipment
						.getInstallPosition());
				localEquipment.setIntersectionName(equipment
						.getIntersectionName());
				localEquipment.setStatus(equipment.getStatus());
				
				return localEquipmentMapper
						.updateByPrimaryKeySelective(localEquipment);
			} else
			{
				equipment.setEquipmentUuid(UUIDGenerateUtil.generate());
				
				// 添加设备与流媒体关系：2015-10-27
				localEquipmentMapper.insertSelective(equipment);
				EquipmentToMedie medieMapInfo = new EquipmentToMedie();
				// 删除重复
				EquipmentToMedieExample exMap = new EquipmentToMedieExample();
				exMap.or().andEquimentUuidEqualTo(equipment.getEquipmentUuid());
				equimentToMedieMapper.deleteByCondition(exMap);
				
				// 设置默认流媒体信息
				medieMapInfo.setUuid(UUIDGenerateUtil.generate());
				medieMapInfo.setEquimentUuid(equipment.getEquipmentUuid());
				medieMapInfo.setViewUrl(MediaCfgManager.instance()
						.getMediaAddress());
				Random random = new Random();
				medieMapInfo.setStream("NO" + random.nextInt() + "-"
						+ equipment.getCameraNo());
				medieMapInfo.setResolution(MediaCfgManager.instance()
						.getDefaultResolution());
				medieMapInfo.setProcessId(equipment.getEquipmentUuid());
				medieMapInfo.setEquipmentViewStream(MediaCfgManager.instance()
						.getDefaultEqumnetAddress(equipment.getCameraIp()));
				
				return equimentToMedieMapper.insertSelective(medieMapInfo);
			}
		} catch (Throwable e)
		{
			throw new BaseException(e.getMessage());
		}
		
	}
	
	@Override
	public LocalEquipment findUniqueEquipment(String equipmentUuid)
	{
		LocalEquipment localEquipment = localEquipmentMapper
				.selectByPrimaryKey(equipmentUuid);
		return localEquipment;
	}
	
	@Override
	public LocalEquipment findUniqueEquipmentByCameraNo(String cameraNo)
	{
		LocalEquipment localEquipment = localEquipmentMapper
				.findUniqueEquipmentByCameraNo(cameraNo);
		return localEquipment;
	}
	
	@Override
	public BaseMapper<LocalEquipmentExample, LocalEquipment, String> getMapper()
	{
		// TODO Auto-generated method stub
		return localEquipmentMapper;
	}
	
	@Override
	public Integer deleteBatchById(List<String> ids) throws BaseException
	{
		try
		{
			
			for (String id : ids)
			{
				localEquipmentMapper.deleteByPrimaryKey(id);
				// 删除路口与相机关系表
				CrossingToEquipmentExample mmEx = new CrossingToEquipmentExample();
				mmEx.or().andEquipmentUuidEqualTo(id);
				croToEquimentMpper.deleteByCondition(mmEx);
			}
			EquipmentToMedieExample medieEx = new EquipmentToMedieExample();
			medieEx.or().andEquimentUuidIn(ids);
			equimentToMedieMapper.deleteByCondition(medieEx);
			
		} catch (Throwable e)
		{
			throw new BaseException(e.getMessage(), e);
		}
		return null;
	}
	
	@Override
	public Integer modifyMedieInfo(EquipmentToMedie medieMapInfo)
			throws BaseException
	{
		try
		{
			
			return equimentToMedieMapper
					.updateByPrimaryKeySelective(medieMapInfo);
		} catch (Throwable t)
		{
			throw new BaseException(t.getMessage(), t);
		}
		
	}
	
	@Override
	public EquipmentToMedie getMedieInfoByEquimentId(String equmentId)
	{
		EquipmentToMedieExample ex = new EquipmentToMedieExample();
		ex.or().andEquimentUuidEqualTo(equmentId.trim());
		List<EquipmentToMedie> list = equimentToMedieMapper
				.selectByCondition(ex);
		return list.isEmpty() ? null : list.get(0);
	}
	
	@Override
	public Integer connectionMedie(List<String> equimentIds)
			throws BaseException
	{
		try
		{
			
			EquipmentToMedieExample ex = new EquipmentToMedieExample();
			ex.or().andEquimentUuidIn(equimentIds);
			List<EquipmentToMedie> list = equimentToMedieMapper
					.selectByCondition(ex);
			
			for (EquipmentToMedie mediaInfo : list)
			{
				ProcessMaager.instance().killVidoProtocolConvertRunble(
						mediaInfo.getProcessId());
				
				streamService.createConnect(mediaInfo.getProcessId(),
						mediaInfo.getEquipmentViewStream(),
						mediaInfo.getResolution(), mediaInfo.getViewUrl() + "/"
								+ mediaInfo.getStream(), false);
			}
			
			return null;
		} catch (Throwable t)
		{
			throw new BaseException(t.getMessage(), t);
		}
	}
	
	@Override
	public Integer disconnectMedie(List<String> equimentIds)
			throws BaseException
	{
		try
		{
			
			EquipmentToMedieExample ex = new EquipmentToMedieExample();
			ex.or().andEquimentUuidIn(equimentIds);
			List<EquipmentToMedie> list = equimentToMedieMapper
					.selectByCondition(ex);
			
			for (EquipmentToMedie mediaInfo : list)
			{
				// 防止进程占用现象
				ProcessMaager.instance().getRunbleMaper()
						.remove(mediaInfo.getProcessId());
				
				ProcessMaager.instance().killVidoProtocolConvertRunble(
						mediaInfo.getProcessId());
				
			}
			
			return 1;
		} catch (Throwable t)
		{
			throw new BaseException(t.getMessage(), t);
		}
	}
	
	@Override
	public void modifyEquiment(String id)
	{
		LocalEquipment localEquipment = localEquipmentMapper
				.selectByPrimaryKey(id);
		if ("1".equals(localEquipment.getInstallEffect()))
		{
			localEquipment.setInstallEffect("2");
		} else
		{
			localEquipment.setInstallEffect("1");
		}
		localEquipmentMapper.updateByPrimaryKey(localEquipment);
	}
}
